package com.chaosyeb.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chaosyeb.server.mapper.MenuRoleMapper;
import com.chaosyeb.server.pojo.MenuRole;
import com.chaosyeb.server.pojo.RespBean;
import com.chaosyeb.server.service.IMenuRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Chaos
 * @since 2021-12-04
 */
@Service
public class MenuRoleServiceImpl extends ServiceImpl<MenuRoleMapper, MenuRole> implements IMenuRoleService {

    @Autowired
    private MenuRoleMapper menuRoleMapper;

    /**
     * 更新角色菜单
     *
     * @param rid
     * @param mids
     * @return
     */
    @Override
    @Transactional
    public RespBean updateMenuRole(Integer rid, Integer[] mids) {
        //先根据rid，先清空，再插入
        menuRoleMapper.delete(new QueryWrapper<MenuRole>().eq("rid", rid));
        //判断是否为空
        if (mids == null || mids.length == 0) {
            return RespBean.success("更新成功！");
        }
        //判断mids是否超过最大值28
        //Arrays.sort(mids)
        int temp = mids[0];
        //菜单最大值为28
        int midMax = 28;
        for (int i = 0; i < mids.length; i++) {
            if (mids[i] > temp) {
                temp = mids[i];
            }
        }
        if (temp > midMax) {
            return RespBean.error("要修改的菜单不存在");
        }

        //如果mids不为空，则插入
        Integer result = menuRoleMapper.insertRecord(rid, mids);
        // 判断插入的条数是否等于mids的长度
        if (result == mids.length) {
            return RespBean.success("更新成功！");
        }
        return RespBean.error("更新失败！");
    }
}
